package com.adingxiong.quickstart.util;



import com.baomidou.mybatisplus.extension.api.Assert;
import okhttp3.*;

/**
 * @ClassName HttpUtils
 * @Description   Http 请求第三方接口工具类
 * @Author xiongchao
 * @Date 2020/7/29 16:33
 **/
public class HttpUtil {

    public static final MediaType JSON  = MediaType.get("application/json;charset=utf-8");


    private static OkHttpClient client = new OkHttpClient();

    public static String doGet (String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        return getResponse(request);
    }

    private static String getResponse(Request request) {
        try {
            Response res = client.newCall(request).execute();
            return res.body().string();
        } catch (Exception e){
            Assert.fail("request_error");
            return null;
        }
    }

    //Post请求

    public static String doPost (String url ,String json) {
        RequestBody body = RequestBody.create(JSON,json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return getResponse(request);
    }

}
